<?php
/**
 * author:式神(289650682@qq.com)
 * time:2017-03-08
 */
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/admin';
    //protected $username;

    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
        //->username = config('admin.global.username');
    }

	//登陆
    public function showLogin(){
    	return view('admin.login');
    }

    public function login(Request $request){
        if ($request->isMethod('post')) {
            $validator = $this->validateLogin($request->input());
            if ($validator->fails()){
                $data=[
                    "status"=>300,
                    "msg"=>$validator->messages()->first()
                ];
                return back()->withErrors($validator)->withInput();
            }
            if ( auth('admin')->attempt(['email'=>$request->email, 'password'=>$request->password, 'status' => 1])) {
                $data=[
                    "status"=>200,
                    "msg"=>trans('config.loginSuccess')
                ];
            } else {
                $data=[
                    "status"=>300,
                    "msg"=>trans('config.loginError')
                ];
            }
            return $data;
        }
    }

    //注销
    public function logout(){
        if(auth('admin')->user()){
            auth('admin')->logout();
        }
        return redirect('admin/login');
    }

    //登录页面验证
    protected function validateLogin(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|email',
            'password' => 'required',
        ], [
            'required' => ':attribute '.trans('config.required'),
            'min' => ':attribute '.trans('config.min')
        ], [
            //'name' => trans('config.user'),
            'email' => trans('config.email'),
            'password' => trans('config.password')
        ]);
    }

    /**
     * 自定义认证驱动
     * @author 晚黎
     * @date   2016-09-05T23:53:07+0800
     * @return [type]                   [description]
     */
    protected function guard()
    {
        return auth()->guard('admin');
    }
}
